# Listener for RSS feeds
# This listener is the archetypal listener module

import plobject, listenboard # Needs to be included in every listener
import time
import json, threading		# We are so 2.6
import feedparser			# Lives in the mods folder for now

class FeedListener():
	def __init__(self, stuff):
		self.params = stuff
		self.started = time.time()
		self.pluid = stuff[0]
		self.received = []			# List of the things received on the feed
		#print self.pluid			# Tie the instance to someone in the plexbase
		#print stuff
		#print stuff[2]
		specifics = json.loads(self.params[2])
		#print(params)
		for thingy in specifics:
			print thingy
			# These next lines are highly dependent on a particular order in the jcard
			# That is wrong, evil bad, and will need to be changed.  Eventually.
			if (thingy[0] == 'feed'):
				print(thingy[1])		# Extract the URL for the feed
				self.url = thingy[1]
			if (thingy[0] == 'id'):
				self.id = thingy[1]
			else:
				self.id = 'feed'

	def running(self):
		while True:
			# Check the feed, is there anything new there?
			matched = False
			newtime = 0
			feed = feedparser.parse(self.url)	# Will puke if it ain't a valid URL?
			#print feed
			num_articles = len(feed['entries']) 
			if (num_articles > 0):		# At least one entry here?
				#print ("Feed has " + str(num_articles) + " entries.")
				for article in feed['entries']:
					article_timestamp = time.mktime(article['updated_parsed']) - time.timezone	# Get article timestamp, correct for timezone
					#print(str(article_timestamp) + " vs. " + str(self.started))
					if (article_timestamp > self.started):
						print("NEW ARTICLE on " + self.url)
						matched = True
						if (article_timestamp > newtime):
							newtime = article_timestamp
						
						# OK, we gotta start pulling stuffs out of this
						# So that it get passed along
						# For the moment, let's pull the title
						# And leave it at that.
						# We can get fancier later.
						title = article.title
						#print title
						# Hopefully grab the article content here
						bits_of_glory = ''
						if article.has_key('content'):
							print('We can has content!')
							for nugget in article.content:
								if (len(nugget.value) > 0):
									bits_of_glory = bits_of_glory + nugget.value
						to_send = plobject.Plobject(pluid=self.pluid, type="text/html", plob=bits_of_glory, title=title, timestamp=article_timestamp, id=self.id)
						self.received.append(to_send)
						listenboard.send_listened(to_send)		# Send it off to enque with other listend stuff

			if (matched == True):
				self.started = newtime 		# Update the time			
			time.sleep(15)		# And sleep for 5 minutes
			#print("Feed listener waking up: " + self.url)



# This function must be implemented in every listener
def instance(stuff):
	#print("Instancing feed listener")
	thelistener = FeedListener(stuff)
	#print("Feed listener object instanced")
	listener_thread = threading.Thread(target=thelistener.running)
	listener_thread.name = "Feed listener thread"
	listener_thread.start()
	#print("Feed listener thread instanced")

if __name__ == '__main__':
	fakestuff = (u'9fd70336-4c41-4b60-9bb5-3b65bcb8d047', 
					u'feed', 
					u'[["feed", "http://en.wikipedia.org/w/index.php?title=Special:RecentChanges&feed=atom"], ["id", "Wikipedia Change Feed"]]')
# 	fakestuff = (u'9fd70336-4c41-4b60-9bb5-3b65bcb8d047', 
# 					u'feed', 
# 					u'[["feed", "http://twitter.com/statuses/public_timeline.rss"], ["id", "Twitter Public Feed"]]')
	instance(fakestuff)